using Microsoft.SqlServer.Management.Smo;
using System;
using System.Collections.Specialized;
using System.Globalization;

namespace Microsoft.SqlServer.Management.SqlManagerUI.Scripting
{
using Server = Microsoft.SqlServer.Management.Smo.Server;
	internal class ScriptDatabaseTriggerCommand : ScriptObjectCommand
	{
		private const string _enableTrigger = "Enable Trigger {0} ON Database";

		private const string _disableTrigger = "Disable Trigger {0} ON Database";

		private const string _ifExistsCheck = "IF {0} EXISTS (SELECT * FROM sys.triggers WHERE parent_class_desc = 'DATABASE' AND name = N'{1}')\r\nBegin\r\n{2}\r\nEnd";

		public ScriptDatabaseTriggerCommand(Server server, ObjectScriptedHandler scriptTarget, ScriptActions scriptAction) : base(server, scriptTarget, scriptAction)
		{
		}

		protected override void ScriptCreate(SqlSmoObject smoObject, ScriptingOptions options, ObjectScriptedHandler scriptTarget)
		{
			if (!(smoObject is DatabaseDdlTrigger))
			{
				base.ScriptCreate(smoObject, options, scriptTarget);
				return;
			}
			DatabaseDdlTrigger databaseDdlTrigger = smoObject as DatabaseDdlTrigger;
			bool isEnabled = databaseDdlTrigger.IsEnabled;
			databaseDdlTrigger.IsEnabled = false;
			base.ScriptCreate(databaseDdlTrigger, options, scriptTarget);
			databaseDdlTrigger.IsEnabled = isEnabled;
			if (isEnabled)
			{
				StringCollection stringCollection = new StringCollection();
				stringCollection.Add(string.Format(CultureInfo.InvariantCulture, "Enable Trigger {0} ON Database", new object[]
				{
					this.GetName((DatabaseDdlTrigger)smoObject)
				}));
				scriptTarget(new ObjectInfo(databaseDdlTrigger.Name, databaseDdlTrigger.Urn), stringCollection, ScriptActions.EnableDDLTrigger);
			}
		}

		protected override void ScriptDrop(SqlSmoObject smoObject, ScriptingOptions options, ObjectScriptedHandler scriptTargetHandler)
		{
			base.ScriptDrop(smoObject, options, scriptTargetHandler);
			if (!(smoObject is DatabaseDdlTrigger))
			{
				return;
			}
			DatabaseDdlTrigger databaseDdlTrigger = smoObject as DatabaseDdlTrigger;
			string text = string.Format(CultureInfo.InvariantCulture, "Disable Trigger {0} ON Database", new object[]
			{
				this.GetName(databaseDdlTrigger)
			});
			string value = string.Format(CultureInfo.InvariantCulture, "IF {0} EXISTS (SELECT * FROM sys.triggers WHERE parent_class_desc = 'DATABASE' AND name = N'{1}')\r\nBegin\r\n{2}\r\nEnd", new object[]
			{
				"",
				databaseDdlTrigger.Name,
				text
			});
			StringCollection stringCollection = new StringCollection();
			stringCollection.Add(value);
			scriptTargetHandler(new ObjectInfo(databaseDdlTrigger.Name, databaseDdlTrigger.Urn), stringCollection, ScriptActions.DisableDDLTrigger);
		}

		private string GetName(DatabaseDdlTrigger trigger)
		{
			return string.Format(CultureInfo.InvariantCulture, "[{0}]", new object[]
			{
				trigger.Name
			});
		}
	}
}
